# Create your views here.

from django.template import Context, loader
from django.http import Http404,HttpResponseRedirect,HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.core.urlresolvers import reverse

from qa.secret.models import ACL, Coin, QRole, Question, Answer
import json

def __create_question(question, questioner, answerers, targets):
    #questioner, answerer, target
    #buf = request.raw_post_data
    #result = json.loads(buf)
    #question = result['question']
    #questioner = result['questioner']
    #answerers = result['answerers']
    #targets = result['targets']
    
    #todo, add transaction for two tables
    
    #insert question record
    q = Question(question)
    q.save()
    
    #insert role record
    q_role = QRole(question=q, user=questioner, role='Q')
    q_role.save()
    
    for i in answerers:
        a_role = QRole(question=q, user=i, role='A')
        a_role.save()
        
    for i in targets:
        t_role = QRole(question=q, user=i, role='T')
        t_role.save()
        
def __answer_question(questionid, answer):
    #buf = request.raw_post_data
    #result = json.loads(buf)
    
    questionid = result['questionid']
    answer = result['answer']
    
    ans = Answer(question=questionid, user=request.user, answer=answer)
    ans.save()
    
def __get_questions(user):
    #get all question for the user and pick out those haven't answer yet
    q_set = set([ i.question for i in QRole.objects.filter(user=user, role='A')])
    ans_set = set([ i.question for i in Answer.objects.filter(user=request.user)])
    unanswered = q_set - ans_set
    
    return unanswered

def __get_answers(questionid):
    return Answer.objects.filter(question=questionid)
    
    